package com.cndongtai.tag;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cndongtai.constant.SystemConstant;

public class PageDownTag extends SimpleTagSupport{
	private int nowPage; // 当前页，默认为第一页
	private int totalSize; // 总条数
	private int pageSize; // 每页条数
	private String form; //分页数据所在的表单id

	@Override
	public void doTag() throws JspException, IOException {
		HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 
	    String path = request.getContextPath();
		StringBuffer sb = new StringBuffer();// 用于拼接分页字符串
		PageContext pc = (PageContext) this.getJspContext();
		JspWriter out = pc.getOut();// 获取输出流out对象
		int totalPages = this.getTotalPage(totalSize, pageSize);//算出总页数
		
		String language = (String) request.getSession().getAttribute(SystemConstant.LANGUAGE);
		String lastPageTitle = "上一页";
		String nextPageTitle = "下一页";
				
    	if(!"zh".equals(language)) {
    		lastPageTitle = "LastPage";
    		nextPageTitle = "NextPage";
    	}
		
		if (totalSize <=0) {
			sb.append("<div class='none_div'>很遗憾，没有找到您要的信息...</div>");
		}
		
		sb.append("<div><nav aria-label=\"Page navigation example\"><ul class=\"pagination justify-content-center\">");
		
		//当前页为1则首页和上一页无链接
		if (nowPage==1 || totalPages<=1) {
			sb.append("<li class=\"page-item disabled\"><a class=\"page-link\" href=\"#\" tabindex=\"-1\">"+lastPageTitle+"</a></li>");
		} else {
			sb.append("<li class=\"page-item\"><a onclick=\"goPage('UpPage');\" class=\"page-link\" href=\"javascript:void(0);\" tabindex=\"-1\">"+lastPageTitle+"</a></li>");
		}
		
		// 下面的代码显示页码，当前页在中间位置
		if (totalPages <= 8) {//如果总页数小于或等于5页，则显示全部
			for (int i = 1; i < totalPages + 1; i++) {
				if (i == nowPage) {// 如果页码等于当前页，则该页数没有链接
					sb.append("<li class=\"page-item\">");
					sb.append("<a class=\"page-link bg-nowpage disabled\" href=\"javascript:void(0);\">");
					sb.append(i);
					sb.append("</a></li> ");
				} else {// 否则给出超链接
					sb.append("<li class=\"page-item\"><a class=\"page-link\" onclick='goPage("+i+");' href=\"javascript:void(0);\">");
					sb.append(i);
					sb.append("</a></li> ");
				}
			}
		} else {// 大于5页，则显示5页
			int index = 1;
			if (this.nowPage > 7) {// 并且如果当前页大于4页，从当前页前2页开始显示5个页数
				for (int j = this.nowPage - 2; j <= totalPages; j++) {
					if (j == nowPage) {// 如果页码等于当前页，则该页数没有链接
						sb.append("<li class=\"page-item\">");
						sb.append("<a class=\"page-link bg-nowpage disabled\" href=\"javascript:void(0);\">");
						sb.append(j);
						sb.append("</a></li> ");
					} else {// 否则给出超链接
						sb.append("<li class=\"page-item\"><a class=\"page-link\" onclick='goPage("+j+");' href=\"javascript:void(0);\">");
						sb.append(j);
						sb.append("</a></li> ");
					}
					
					index++;
					if (index > 8)// 如果循环到5次则退出循环
						break;
				}
			} else {// 并且如果当前页小于等于3页
				for (int i = 1; i <= totalPages; i++) {
					// 如果页数小于等于5页,则全部显示
					if (i == nowPage) {// 如果页码等于当前页，则该页数没有链接
						sb.append("<li class=\"page-item\">");
						sb.append("<a class=\"page-link bg-nowpage disabled\" href=\"javascript:void(0);\">");
						sb.append(i);
						sb.append("</a></li> ");
					} else {// 否则给出超链接
						sb.append("<li class=\"page-item\"><a class=\"page-link\" onclick='goPage("+i+");' href=\"javascript:void(0);\">");
						sb.append(i);
						sb.append("</a></li> ");
					}
					
					index++;
					if (index > 8){// 如果循环到5次则退出循环
						break;
					}
				}
			}
		}
		
		// 如果当前页是最后一页，则末页和下一页没有超链接
		if (this.nowPage == totalPages || totalPages<=1) {
			sb.append("<li class=\"page-item disabled\"><a class=\"page-link\" href=\"#\">"+nextPageTitle+"</a></li>");
		} else {
			sb.append("<li class=\"page-item\"><a class=\"page-link\" onclick=\"goPage('nextPage');\" href=\"javascript:void(0);\">"+nextPageTitle+"</a></li>");
		}
		
		sb.append("</ul></nav></div>");
		
		// 一下代码拼接转到第几页的js代码
		sb.append("<script type='text/javascript'>");
		sb.append("function getPage(){");
		
		//没有数据
		if(totalSize <= 0){
			sb.append("alert('无记录,无法进行页码跳转！');" + "$('#pageText').val("+nowPage+");" + "return false;}");
		}else{
			sb.append("var pageIndex = document.getElementById('pageText').value.trim();");
			//判断要跳转的页面是否为数字，如果不是数字，则不能跳转
			sb.append("if(!/^[1-9]\\d*$/.test(pageIndex)){" + "alert('页码只能输入正整数！');" + "return false;" + "}");
			sb.append("if(pageIndex>"+totalPages+"){alert('共"+totalPages+"页,无法跳转到'+pageIndex+'页！');" + "$('#pageText').val("+nowPage+");" +"return false;}");
			sb.append("$('#pageSize').val("+pageSize+");$('#nowPage').val(pageIndex);");
			sb.append("document."+form+".submit();}");
		}
		
		sb.append("</script>");
		
		
		sb.append("<script type='text/javascript'>");
		sb.append("function EnterPress(e){var e = e || window.event;if(e.keyCode == 13){getPage();}} ");
		sb.append("function setPageSize(value){$('#pageSize').val(value);" + "$('#nowPage').val(1);" + "document."+form+".submit();} ");
		sb.append("" +
				"function goPage(nowPage){" +
				"if(nowPage == 'firstPage'){$('#pageSize').val("+pageSize+");$('#nowPage').val(1);}" +
				"else if(nowPage == 'UpPage'){$('#pageSize').val("+pageSize+");$('#nowPage').val("+(nowPage - 1)+");}" +
				"else if(nowPage == 'nextPage'){$('#pageSize').val("+pageSize+");$('#nowPage').val("+(nowPage + 1)+");}" +
				"else if(nowPage == 'lastPage'){$('#pageSize').val("+pageSize+");$('#nowPage').val("+totalPages+");}" +
				"else{$('#pageSize').val("+pageSize+");$('#nowPage').val(nowPage);}" +
				"document."+form+".submit();} " + "</script>");
		out.print(sb);
	}

	/**
	 * 获取总页数
	 * 
	 * @return
	 */
	public int getTotalPage(int totalSize, int pageSize) {
		int result = 0;
		if (totalSize % pageSize == 0) {
			result = totalSize / pageSize;
		} else {
			result = totalSize / pageSize + 1;
		}

		return result;
	}
	
	public boolean isNumber(String str){
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if(!isNum.matches()){
			return false;
		}
		return true;
	}
	
	public int getNowPage() {
		return nowPage;
	}

	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}

	public int getTotalSize() {
		return totalSize;
	}

	public void setTotalSize(int totalSize) {
		this.totalSize = totalSize;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String getForm() {
		return form;
	}

	public void setForm(String form) {
		this.form = form;
	}

}
